/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.app.brilliant.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取IP地址工具类
 * @author geekidea
 * @date 2018-11-08
 */
@Slf4j
public final class IpUtil {

    private static DbSearcher searcher;

    static {
        try {
            String dbPath = IpUtil.class.getResource("/config/ip2region.db").getPath();
            File file = new File(dbPath);
            if (!file.exists()) {
                log.error("Error: Invalid ip2region.db file");
            }
            DbConfig config = new DbConfig();
            searcher = new DbSearcher(config, dbPath);
        } catch (FileNotFoundException | DbMakerConfigException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private IpUtil(){
        throw new AssertionError();
    }

    /**
     * 获取请求用户的IP地址
     * @return
     */
    public static String getRequestIp() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return getRequestIp(request);
    }

    /**
     * 获取请求用户的IP地址
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("X-real-ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)){
            ip = getLocalhostIp();
        }
        return ip;
    }

    public static String getLocalhostIp(){
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignored) {
        }
        return null;
    }


    public static IpData searchIp(String ip) throws IOException {
        if (searcher == null) {
            log.error("searcher");
        }
        DataBlock dataBlock = searcher.btreeSearch(ip);
        if (dataBlock == null) {
            log.error("dataBlock");
        }
        String region = dataBlock.getRegion();
        String[] split = region.split("\\|");
        IpData data = new IpData();
        data.setCountry(split[0]);
        data.setRegion(split[1]);
        data.setProvince(split[2]);
        data.setCity(split[3]);
        data.setOperator(split[4]);
        return data;
    }

    @Data
    public static class IpData {

        //国家
        private String country;

        //大区
        private String region;

        //省份
        private String province;

        //城市
        private String city;

        //运营商
        private String operator;

    }

    public static void main(String[] args) throws DbMakerConfigException, IOException {
        //ip
        String ip="220.248.12.158";
        //打印位置信息（格式：国家|大区|省份|城市|运营商）
        IpData data = IpUtil.searchIp(ip);
        System.out.println(data);
//        System.err.println(getCityInfo("220.248.12.158"));
    }

}
